package com.backend.struts;

import com.backend.models.ProductComment;
import com.backend.utils.CommonStringUtils;
import lombok.Getter;

import java.util.*;
import java.util.stream.Collectors;

public class CommentObj {
    public ProductComment comment;
    public List<CommentObj> commentObjs;
    public String username;
    public String userImg;
    public String reUsername;
    public String date;
    public Integer userId;
    public CommentObj(ProductComment productComment, List<ProductComment> productComments, Map<Integer, Map<String,String>> userMap){
        comment = productComment;
        Map<String,String> tempMap = userMap.getOrDefault(CommonStringUtils.safeString(comment.userId),new HashMap<>());
        if(comment.reComment != null) {
            Map<String, String> reMap = userMap.getOrDefault(CommonStringUtils.safeString(comment.reComment.userId), new HashMap<>());
            reUsername = reMap.get("username");
        }
        username = tempMap.get("username");
        userImg = tempMap.get("img_path");
        userId = productComment.userId;
        date = CommonStringUtils.DateToStr(comment.createTime);
        List<ProductComment> productCommentList = productComments.stream().filter(comment1 -> comment.equals(comment1.reComment))
                .sorted(Comparator.comparing(o -> o.createTime)).collect(Collectors.toList());
        productComments.removeAll(productCommentList);
        commentObjs = new ArrayList<>();
        if(productCommentList.size() != 0) {
            productCommentList.forEach(productComment1 -> {
                commentObjs.add(new CommentObj(productComment1, productComments,userMap));
            });
        }
    }

    public List<CommentObj> getCommentObjs(){
        return this.commentObjs;
    }

}
